package com.tsingteng.cosfun.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.DialogHelper;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.widget.ContainerLayout;
import com.umeng.analytics.MobclickAgent;

import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.content.Context.POWER_SERVICE;

/**
 * 描述:fragment 基类
 * 创建人: 肖利
 * 时间: 2018/7/30
 * qq: (872179966)
 */

public abstract class BaseFragment extends Fragment {

    private Unbinder unbinder;
    public View rootView;
    private Dialog mLoadingDialog;
    public ContainerLayout mContain;
    public FrameLayout mContent;
    private Dialog mHintDialog;
    private PowerManager pm;
    private PowerManager.WakeLock wl;

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        //手动保存
        outState.putBoolean(Config.ARG_IS_HIDDEN, isHidden());
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i("BaseFragment", getClass().getSimpleName() + " onCreate("
                + (savedInstanceState == null ? "" : savedInstanceState) + ")");
        initFragments(savedInstanceState,this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            getBundle(bundle);
        }
        //管理屏幕常亮状态
        pm = (PowerManager) getActivity().getSystemService(POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                getResources().getString(R.string.app_name));

        mLoadingDialog = DialogHelper.getLoadingDialog(getContext());
        mHintDialog = DialogHelper.getHintDialog(getContext());
    }

    /**
     * '
     * 初始化UI
     */
    protected abstract void initView();


    protected abstract void getBundle(Bundle bundle);

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getLayoutId() != 0) {
            rootView = inflater.inflate(R.layout.fragment_base, container, false);
            mContain = rootView.findViewById(R.id.containerLayout);
            mContent = rootView.findViewById(R.id.fl_content);
            mContent.addView(View.inflate(getContext(), getLayoutId(), null));
            unbinder = ButterKnife.bind(this, rootView);
            initView();
            return rootView;
        } else {
            throw new IllegalStateException("请初始化布局");
        }

    }

    /**
     * 屏幕常亮
     */
    public void bright() {
        try {
            wl.acquire();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消常亮
     */
    public void cancelBright() {
        try {
            wl.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @return
     */
    public boolean onBackPressed() {
        return false;
    }

    /**
     * 显示加载框
     */
    protected void showLoadingDialog() {
        if (mLoadingDialog != null ) {
            if (mLoadingDialog.isShowing()) return;
            mLoadingDialog.show();
        }

    }

    /**
     * 显示提示消息的提示框
     * @param text
     */
    protected void showHintDialog(String text) {
        if (mHintDialog != null) {
            TextView tv = mHintDialog.findViewById(R.id.tv_load_dialog);
            tv.setText(text);
            mHintDialog.show();
        }
    }

    /**
     * 显示带有消息的加载框
     *
     * @param str
     */
    protected void showLoadingDialog(String str) {
        if (mLoadingDialog != null) {
            TextView tv = mLoadingDialog.findViewById(R.id.tv_load_dialog);
            tv.setText(str);
            mLoadingDialog.show();
        }
    }

    /**
     * 隐藏加载框
     */
    protected void hideHintDialog() {
        if (mHintDialog != null && mHintDialog.isShowing()) {
            mHintDialog.dismiss();
        }
    }

    /**
     * 隐藏加载框
     */
    protected void hideLoadingDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            Context context = ((ContextWrapper)mLoadingDialog.getContext()).getBaseContext();
            if(context instanceof Activity) {
                 if (!((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) {
                     mLoadingDialog.dismiss();
                 }
            }
        }
    }

    /**
     * 吐司
     *
     * @param msg
     */
    protected void showToast(String msg) {
        ToastUtils.showToast(msg);
    }

    /**
     * 布局文件加载
     *
     * @return
     */
    protected abstract int getLayoutId();

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

//    /**
//     * 检查登录
//     * @return
//     */
//    public boolean chckLogon(int type) {
//        if (!LogonUtils.getIsLogin()) {
//            Navigate.startLogon(getContext(),true,type);
//            return false;
//        }
//        return true;
//    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.i("BaseFragment", getClass().getSimpleName() + " onResume");
        MobclickAgent.onResume(getActivity());
    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtils.i("BaseFragment", getClass().getSimpleName() + " onPause");
        MobclickAgent.onPause(getActivity());
    }

    //onCreate的时候调用
    public void initFragments(Bundle savedInstanceState, BaseFragment fragment) {
        if (savedInstanceState == null) {
            return;
        }
        boolean isSupportHidden = savedInstanceState.getBoolean(Config.ARG_IS_HIDDEN);
        if (getActivity()==null)return;
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        if (isSupportHidden) {
            ft.hide(fragment);
        } else {
            ft.show(fragment);
        }
        ft.commit();
        super.onDetach();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        LogUtils.i("BaseFragment", getClass().getSimpleName() + " onDetach");
    }
}
